<template>
  <div class="media">
    <div class="video-area">
      <video class="video" width="100%" height="auto" ref="video" autoplay :srcObject="videoSource">
        Video stream not available.
      </video>
      <canvas width="500" height="375" ref="canvas" id="canvas" />
      <img class="image" width="100%" height="100%" :src="photoSource" v-if="photoSource" />
    </div>

    <div class="button-container">
      <button class="capture-button" @click="takePhoto">确认拍照</button>
      <button class="capture-button" @click="retakePhoto">重拍</button>
      <button class="capture-button" @click="startDiagnosis" :disabled="!photoSource">开始诊断</button>
    </div>

    <!-- 动态加载条模态框 -->
    <div class="modal" @click="handleOutsideClick" v-if="isProcessing">
      <div class="modal-dialog" @click.stop>
        <div class="modal-content">
          <div class="modal-body">
            <p style="font-weight: bold; font-size:x-large;">正在诊断，请稍后...</p>
            <div class="loading-bar">
              <div class="loading-line"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 网络提示框 -->
    <div v-if="showNetworkError" class="network-error">
      <p>网络不佳，请稍后再试</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      url: {
        diagnose: '/palm/diagnose'
      },
      videoSource: null,
      photoSource: null,
      caseNo: 234,
      isProcessing: false,
      cameraName: 'USB2.0 Camera RGB',
      selectedCameraId: null,
      showNetworkError: false,  // 网络错误提示
      timeoutId: null,  // 用于保存超时定时器
    };
  },

  mounted() {
    this.initializeCamera();
  },

  methods: {
    async initializeCamera() {
      try {
        console.log('开始搜索摄像头');
        navigator.mediaDevices.getUserMedia({ audio: true, video: true });
        const devices = await navigator.mediaDevices.enumerateDevices();
        const camera = devices.find(device => device.kind === 'videoinput' && device.label.includes(this.cameraName));
        console.log('Available devices:', devices);
        console.log('Available camera:', camera);

        const targetCamera = devices.find(device =>
          device.kind === 'videoinput' && (device.label || '').includes(this.cameraName)
        );

        if (targetCamera) {
          this.selectedCameraId = targetCamera.deviceId;
          console.log(`Selected camera ID: ${this.selectedCameraId}, with label: ${targetCamera.label}`);
          await this.changeCamera();
        } else {
          console.error(`No video devices with the name "${this.cameraName}" found.`);
        }
      } catch (error) {
        console.error('Error initializing camera:', error);
      }
    },

    async changeCamera() {
      try {
        console.log('选择摄像头：', this.selectedCameraId);
        if (!this.selectedCameraId) return;
        const constraints = { video: { deviceId: { exact: this.selectedCameraId } }, audio: false };
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        console.log('Got stream:', stream);
        this.$refs.video.srcObject = stream;
        this.$refs.video.play().catch(error => {
          console.error('Failed to play video:', error);
        });
        this.videoSource = stream;
      } catch (error) {
        console.error('Error accessing the camera:', error);
      }
    },

    takePhoto() {
      const canvas = this.$refs.canvas;
      const video = this.$refs.video;

      if (!canvas || !video) {
        console.error('Canvas or video is undefined.');
        return;
      }

      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, 500, 375);
      this.photoSource = canvas.toDataURL('image/jpeg');
      console.log(this.photoSource);
    },

    retakePhoto() {
      this.photoSource = null;
    },

    async startDiagnosis() {
      try {
        this.isProcessing = true;
        this.showNetworkError = false;  // 隐藏网络错误提示

        // 设置 15 秒超时
        this.timeoutId = setTimeout(() => {
          this.isProcessing = false;
          this.showNetworkError = true;  // 显示网络错误提示
        }, 30000);  // 15秒超时

        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const caseNo = `${year}${month}${day}${hours}${minutes}${seconds}`;

        const imageBlob = await this.dataUrlToBlob(this.photoSource);
        console.log('图片信息:', imageBlob);

        const formData = new FormData();
        formData.append('file', imageBlob, `${caseNo}.png`);
        formData.append('caseNo', caseNo);
        console.log('发送信息:', formData);

        // 发送请求并在 15 秒内等待响应
        const response = await axios.post(`${this.URLhost}${this.url.diagnose}`, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        clearTimeout(this.timeoutId);  // 请求成功后清除超时定时器
        
          
        // 处理诊断结果
        const reason = response.data.data.data.reason;
        const symptom = response.data.data.data.symptom;
        const method = response.data.data.data.method;
        localStorage.setItem('reason', symptom);
        localStorage.setItem('symptom', reason);
        localStorage.setItem('method', method);
        console.log('诊断结果:', response);
        this.$router.push('/ResultPalm');
      } catch (error) {
        console.error('诊断请求失败:', error);
        alert('诊断失败，请重试。');
        this.isProcessing = false;
      }
    },

    dataUrlToBlob(dataUrl) {
      return new Promise((resolve) => {
        const byteString = atob(dataUrl.split(',')[1]);
        const arrayBuffer = new ArrayBuffer(byteString.length);
        const uint8Array = new Uint8Array(arrayBuffer);
        for (let i = 0; i < byteString.length; i++) {
          uint8Array[i] = byteString.charCodeAt(i);
        }
        resolve(new Blob([uint8Array], { type: 'image/png' }));
      });
    },

    handleOutsideClick(event) {
      if (event.target === event.currentTarget) {
        this.isProcessing = false;
      }
    },
  },
};
</script>

<style scoped>
/* 确保父容器允许 .media 占据全部可用空间 */
.media {
  background-image: url('@/assets/image/jwCH4bFk.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  /* 固定背景 */
  height: 100vh;
  /* 铺满整个视口高度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  /* 对齐内容到顶部 */
}

.video-area {
  width: 50%;
  position: relative;
  border: 2px solid #4b4b4b;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  overflow: hidden;
  border-radius: 12px;
  margin-top: 3%;
  /* 下移视频区域 */
}

.video {
  width: 100%;
  height: auto;
  background-image: url('@/assets/image/图片预览.png');
  background-size: cover;
  background-position: center;
  border-radius: 8px;
  border: none;
  transition: transform 0.2s ease;
}

.video:hover {
  transform: scale(1.05);
}

.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: auto;
  object-fit: cover;
  border-radius: 8px;
}

.button-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  width: 40%;
  margin-top: 2rem;
}

.capture-button {
  padding: 30px 40px;
  background: linear-gradient(to right, #1f4224, #a1caac);
  color: white;
  font-size: 200%;
  font-weight: bold;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 4px 15px 0 rgba(95, 255, 140, 0.75);
}

.capture-button:hover {
  background: linear-gradient(to right, #65c24c, #b8f7cc);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px 0 rgba(168, 242, 189, 0.75);
}

#canvas {
  display: none;
}

/* 网络错误提示 */
.network-error {
  position: fixed;
  z-index: 1000;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 20px;
  border-radius: 8px;
  font-size: 18px;
  text-align: center;
}

.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-dialog {
  background-color: #2c2c2c;
  margin: auto;
  padding: 20px;
  border-radius: 10px;
  width: 30%;
  text-align: center;
  animation: fadeIn 0.5s;
}

.modal .loading-bar {
  width: 100%;
  height: 4px;
  background-color: #e0e0e0;
  border-radius: 2px;
  margin-top: 10px;
  overflow: hidden;
  position: relative;
}

.modal .loading-line {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #4caf50;
  animation: loading 3s infinite linear;
}

@keyframes loading {
  0% {
    left: -100%;
  }

  50% {
    left: 0%;
  }

  100% {
    left: 100%;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.modal-body p {
  font-size: 16px;
  color: #e0e0e0;
}
</style>
